package com.fkdx.common.sequence;

import com.fkdx.common.enums.sys.GroupException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * ID生成器工具类
 *
 * @author liujia
 */
@Component
public class SequenceUtil {

    @Resource
    private Map<String, Sequence> sequenceMap;

    @Resource
    private Sequence defaultSequence;

    // fixme 简单写了写可能有线程安全问题
    public long get(String name) {
        Sequence sequence = null;
        if (sequenceMap != null) {
            sequence = sequenceMap.get(name);
        }
        if (sequence == null) {
            if (defaultSequence != null) {
                return defaultSequence.get(name);
            } else {
                throw new GroupException("sequence " + name + " undefined!");
            }
        }
        return sequence.get(name);
    }

    public List<Long> get(String name, int count) {
        List<Long> ids = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            ids.add(get(name));
        }
        return ids;
    }

}
